<template>
  <el-dialog :title="title" :visible="showDialog" width="40%" @close="onClose">
    <el-form ref="deptFormRef" :model="deptForm" :rules="deptFormRules" label-width="110px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" placeholder="0-10个字符" size="medium" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" placeholder="0-10个字符" size="medium" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="deptForm.managerId" placeholder="请选择负责人" size="medium" style="width: 100%" @focus="onFocus">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" placeholder="2-10个字符" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="submit">确定</el-button>
        <el-button size="small">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { delCompanyDepartment, getCompanyDepartment, getCompanyDepartmentId, getSysUserSimple, postCompanyDepartment, putDepartment } from '@/api/department/department'
export default {
  name: 'DeptDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    pid: {
      type: Number,
      default: 0
    }
  },
  data() {
    // 部门名称和已有部门不能重复
    const checkDeptName = async(rule, value, callback) => {
      let res = await getCompanyDepartment()
      if (this.deptForm.id) {
        // 自定义校验规则的时候，要区分环境
      // 编辑状态下：需要对当前编辑的人先去排除掉
        res = res.filter(item => item.id !== this.pid)
      }
      if (res.map(dept => dept.name).includes(value.trim())) {
        callback(new Error(`已经存在${value}部门名称`))
      } else {
        callback()
      }
    }
    const checkDeptCode = async(rule, value, callback) => {
      let res = await getCompanyDepartment()
      if (this.deptForm.id) {
        // 先在所有的部门里面，把自己排除掉
        res = res.filter(item => item.id !== this.pid)
      }
      if (res.map(dept => dept.code).includes(value.trim())) {
        callback(new Error(`已经存在${value}部门编码`))
      } else {
        callback()
      }
    }
    return {
      options: [],
      value: '',
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        managerId: '', // 部门负责人id
        introduce: '', // 部门介绍
        pid: '' // 父级部门的id
      },
      deptFormRules: {
        name:
         [
           { validator: checkDeptName, trigger: 'blur' },
           { required: true, message: '部门名称不能为空', trigger: 'blur' },
           { min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur' }
         ],
        code:
         [
           { validator: checkDeptCode, trigger: 'blur' },
           { required: true, message: '部门编码不能为空', trigger: 'blur' },
           { min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur' }
         ],
        // 部门编码
        introduce:
         [
           { required: true, message: '部门介绍不能为空', trigger: 'blur' },
           { min: 1, max: 100, message: '部门介绍的长度为1-100个字符', trigger: 'blur' }
         ],
        // 部门介绍
        managerId:
         [
           { required: true, message: '部门负责人不能为空', trigger: 'blur' }
         ]
        // 部门负责人id
        // 部门名称
        // pid: '' // 父级部门的id 不需要做校验
      }
    }
  },
  computed: {
    title() {
      return this.deptForm.id ? '编辑部门' : '添加部门'
    }
  },
  methods: {
    onClose() {
      this.$emit('update:showDialog', false)
      // 重置表单数据
      this.$refs.deptFormRef.resetFields()
      // 重置pid
      this.$emit('update:pid', 0)
    },
    async onFocus() {
      const res = await getSysUserSimple()
      this.options = res
    },
    async submit() {
      try {
        // 进行表单验证
        await this.$refs.deptFormRef.validate()
        if (this.deptForm.id) {
          await putDepartment(this.deptForm)
          this.$message.success('编辑部门成功')
        } else {
          this.deptForm.pid = this.pid
          await postCompanyDepartment(this.deptForm)
          this.$message.success('添加部门成功')
        }
        this.onClose()
        this.deptForm.pid = 0
        this.$emit('update-list')
      } catch (error) {
        console.log(error)
      }
    },
    async getDetail(id) {
      const res = await getCompanyDepartmentId(id)
      delete res.createTime
      delete res.managerName
      this.deptForm = res
    },
    async delDetail(pid) {
      await this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCompanyDepartment(pid)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.$emit('update-list')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
